package com.liumuxian.user.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liumuxian.user.dao.UserDao;
import com.liumuxian.user.pojo.User;
import com.liumuxian.user.service.UserService;
import com.liumuxian.user.wx.WeixinToken;
import com.liumuxian.user.wx.WexinUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.codehaus.xfire.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import util.Base64Util;
import util.HttpRequest;
import util.IdWorker;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;

@Slf4j
@Service
@CrossOrigin
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Value("${wx.app_id}")
    private String APP_ID;
    @Value("${wx.app_secret}")
    private String APP_SECRET;
    @Autowired
    private IdWorker idWorker;
    public User login(String code,String encryptedData,String iv){
        /*
         * 获取微信openID
         * https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
         */
        String param = "appid="+APP_ID+"&secret="+APP_SECRET+"&js_code="+code+"&grant_type=authorization_code";
        try {
            String result = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", param);
            WeixinToken weixinToken = JSON.parseObject(result,WeixinToken.class);
            User user= userDao.findByWxopenid(weixinToken.getOpenid());
            if(user==null){
                WexinUserInfo wexinUserInfo= getUserInfo(encryptedData,weixinToken.getSession_key(),iv);
                user = new User();
                user.setId(idWorker.nextId()+"");
                user.setNickname(wexinUserInfo.getNickname());
                user.setAvatar(wexinUserInfo.getAvatarUrl());
                user.setSex(wexinUserInfo.getGender());
                user.setSite(wexinUserInfo.getCountry()+"-"+wexinUserInfo.getProvince()+"-"+wexinUserInfo.getCity());
                user.setLanguage(wexinUserInfo.getLanguage());
                user.setIntegral(0L);
                user.setRegdate(new Date());
                user.setLastdate(new Date());
                user.setState(1);
                user.setWxopenid(weixinToken.getOpenid());
                userDao.save(user);
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("登录失败！");
        }
    }

    @Override
    public void save(User user) {
        user.setId(idWorker.nextId()+"");
        user.setState(1);
        userDao.save(user);
    }

    @Override
    public void update(User user) {
        userDao.saveAndFlush(user);
    }

    @Override
    public void delete(String id) {
        User user = userDao.findById(id).get();
        user.setState(0);
        userDao.saveAndFlush(user);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id).get();
    }

    @Override
    public List<User> findAllGesTate(String id, String nickname, Integer state) {
        return userDao.findAll((Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<Predicate>();
            if (id != null && !StringUtils.isEmpty(id)) {
                predicateList.add(criteriaBuilder.equal(root.get("id"), id));
            }
            if (nickname != null && !StringUtils.isEmpty(nickname)) {
                predicateList.add(criteriaBuilder.like(root.get("nickname"), "%" + nickname + "%"));
            }
            if (state != null && !StringUtils.isEmpty(state)) {
                predicateList.add(criteriaBuilder.ge(root.get("state"), (Number) state));
            }
            return criteriaBuilder.and( predicateList.toArray(new Predicate[predicateList.size()]));
        });
    }

    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     * */
    public static WexinUserInfo getUserInfo(String encryptedData, String sessionKey, String iv) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                WexinUserInfo wexinUserInfo = JSON.parseObject(result,WexinUserInfo.class);
                log.info("微信用户信息：  wexinUserInfo:{} \n result:{}",wexinUserInfo,result);
                return wexinUserInfo;
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
